//
//  DRDragImageView.m
//  DoctorRen
//
//  Created by Macx on 2018/12/1.
//

#import "DRDragImageView.h"
#import <MJRefresh/MJRefresh.h>

@interface DRDragImageView ()

@property (nonatomic, assign)  CGPoint startLocation;

@end

@implementation DRDragImageView

-(instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.userInteractionEnabled = YES;
    }
    return self;
}

-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
    CGPoint pt = [[touches anyObject] locationInView:self];
    self.startLocation = pt;
    [[self superview] bringSubviewToFront:self];
}

-(void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event
{
    CGPoint pt = [[touches anyObject] locationInView:self];
    float dx = pt.x - self.startLocation.x;
    float dy = pt.y - self.startLocation.y;
    CGPoint newcenter = CGPointMake(self.center.x + dx, self.center.y + dy);
    
    //
    float halfx = CGRectGetMidX(self.bounds);
    newcenter.x = MAX(halfx, newcenter.x);
    newcenter.x = MIN(self.superview.bounds.size.width - halfx, newcenter.x);
    
    float halfy = CGRectGetMidY(self.bounds);
    newcenter.y = MAX(halfy , newcenter.y);
    newcenter.y = MIN(self.superview.bounds.size.height - halfy - 44, newcenter.y);
    
    self.center = newcenter;
}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    CGPoint point = self.center;
    if (point.x>[self superview].mj_w/2.0) {
        [UIView animateWithDuration:0.2 animations:^{
            self.mj_x = [self superview].mj_w-self.mj_w;
        }];
    }else{
        [UIView animateWithDuration:0.2 animations:^{
            self.mj_x = 0;
        }];
    }
}

-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
    
}


@end
